import $ from "jquery";
import * as THREE from "three/build/three.module.js";
import TWEEN from "@tweenjs/tween.js";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader";
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";

// console.log('TWEEN', TWEEN)
var Math3D = (function (window, document) {
  function _createRandomCoord(maxR, minR) {
    var r = Math.round(Math.random() * (maxR - minR)) + minR;
    var theta = Math.random() * Math.PI * 2;
    //console.log(theta+"="+theta/Math.PI*180);
    var phi = Math.random() * Math.PI * 2;
    //console.log(phi+"="+phi/Math.PI*180);

    return get3DAxis(theta, phi, r);
  }

  function get3DAxis(theta, phi, r) {
    //X=rsinθcosφ y=rsinθsinφ z=rcosθ
    return {
      x: r * Math.sin(theta) * Math.cos(phi),
      y: r * Math.sin(theta) * Math.sin(phi),
      z: r * Math.cos(theta),
    };
  }

  function get3DAngle(x, y, z) {
    //r=sqrt(x*2 + y*2 + z*2); θ= arccos(z/r); φ=arctan(y/x);
    var r = Math.sqrt(x * x + y * y + z * z);
    return {
      theta: Math.acos(z / r),
      phi: Math.atan(y / x),
      r: r,
    };
  }

  function getAngle(point) {
    return Math.atan2(point.y, point.x); //atan2自带坐标系识别, 注意X,Y的顺序
  }

  function Rotate(source, angle, rudius) {
    //Angle为正时逆时针转动, 单位为弧度
    var A, R;
    A = getAngle(source);
    A += angle; //旋转
    R = Math.sqrt(source.x * source.x + source.y * source.y); //半径
    if (rudius) {
      R -= rudius;
    }
    return {
      x: Math.cos(A) * R,
      y: Math.sin(A) * R,
    };
  }

  function getpositionFromAngel(A, R) {
    //Angle为正时逆时针转动, 单位为弧度
    return {
      x: Math.cos(A) * R,
      y: Math.sin(A) * R,
    };
  }

  return {
    createRandomCoord: _createRandomCoord,
    getAngleByAxis2d: getAngle,
    getRotateAxis2d: Rotate,
    getAxis2dByAngle: getpositionFromAngel,
    get3DAxis: get3DAxis,
    get3DAngle: get3DAngle,
  };
})(window, document, undefined);

var lineMaterial = new THREE.LineBasicMaterial({
  // 线的颜色
  color: "#f83005",
  transparent: true,
  opacity: 0.8,
  depthFunc: THREE.AlwaysDepth,
});

let treeContainer, containerDom;
let camera,
  scene,
  renderer,
  texture,
  texture1,
  texture2,
  loader,
  selectObject,
  hoverSelectObject,
  labelRenderer,
  pmremGenerator;
var treeControls;
let mouseX = 0,
  mouseY = 0;
let fxtreeObject = [];
var _raycaster = new THREE.Raycaster(); //拾取器
var raycAsix = new THREE.Vector2(); //屏幕点击点二维坐标
var clickObjects = [];
var _curObj = null,
  _isRotateing = false;
var _userView = {};
var boxOffsetHeight = 0;
var boxOffsetWidth = 0;
var positionY = 0;
var positionX = 0;
var mesh;
var mtlPath = "/resources/moles/obj/mole3/";
var objPath = "/resources/moles/obj/mole3/";
var datavFnc = "";
var currentMoles = 1; // 当前显示的是哪个模型 1,2,3
var mole1Loader = 0; // 模型的加载进度
var mole2Loader = 0;
var mole3Loader = 0;
var animationId = "";
treeContainer = $("#space")[0];
const camDefaultPosition = { x: 15, y: 15, z: -15 }; // 摄像机默认视角
const camDefaultTarget = { x: 0, y: 0, z: 0 }; // 摄像机默认目标点
var gltfLoader = new GLTFLoader();
var overallcfg;

function changeScene() {
  // Trigger animation
  var div = document.getElementById("space1");
  div.classList.remove("screen-change");
  div.classList.add("screen-change");
}

function threeInit(cfg, dom) {
  if (dom) {
    containerDom = dom;
    treeContainer = $("#space")[0];
    let pox = treeContainer.getBoundingClientRect();
    boxOffsetWidth = dom[0].offsetWidth;
    boxOffsetHeight = dom[0].offsetHeight;
    positionY = pox.y;
    positionX = pox.x;
  }
  overallcfg = cfg;
  // scene // 场景
  scene = new THREE.Scene();

  // scene.environment = envMap;
  // 摄像机
  // PerspectiveCamera( fov : Number, aspect : Number, near : Number, far : Number )
  // fov — 摄像机视锥体垂直视野角度
  // aspect — 摄像机视锥体长宽比
  // near — 摄像机视锥体近端面
  // far — 摄像机视锥体远端面
  camera = new THREE.PerspectiveCamera(
    50,
    boxOffsetWidth / boxOffsetHeight,
    0.1,
    1000
  );
  camera.position.y = 15;
  camera.position.x = 15;
  camera.position.z = -15;
  // x: 0, y: 1000, z: -1520,
  // scene.add(camera);

  // 坐标轴辅助
  var axes = new THREE.AxesHelper(400);
  // scene.add(axes);

  const hemiLight = new THREE.HemisphereLight();
  hemiLight.name = "hemi_light";
  scene.add(hemiLight);

  const light1 = new THREE.AmbientLight(0xffffff, 1.5);
  light1.name = "ambient_light";
  camera.add(light1);

  const light2 = new THREE.DirectionalLight(0xffffff, 0.8 * Math.PI);
  light2.position.set(0.5, 0, 0.866); // ~60º
  light2.name = "main_light";
  camera.add(light2);

  // const dirLight = new THREE.DirectionalLight( 0xffffff );
  // dirLight.position.set( - 3, 10, - 10 );
  // dirLight.castShadow = true;
  // dirLight.shadow.camera.top = 2;
  // dirLight.shadow.camera.bottom = - 2;
  // dirLight.shadow.camera.left = - 2;
  // dirLight.shadow.camera.right = 2;
  // dirLight.shadow.camera.near = 0.1;
  // dirLight.shadow.camera.far = 40;
  // scene.add( dirLight );

  // 添加环境光
  const ambientLight = new THREE.AmbientLight(0x444444);
  scene.add(ambientLight);

  // 添加定向光线
  var directionalLight = new THREE.DirectionalLight(0xffeedd);
  directionalLight.position.set(100, 100, 100).normalize();
  scene.add(directionalLight);

  // 半球光源
  // var light = new THREE.HemisphereLight('#7d828e', '#7d828e', 0.8);
  // scene.add(light);

  // 点光源
  // const pointLight = new THREE.PointLight(0xffffff, 0.4);
  // pointLight.position.set(250, 250, 250); // 位置
  // scene.add(pointLight);

  // scene.add(new THREE.PointLightHelper(directionalLight));
  // scene.add(new THREE.PointLightHelper(light));
  // scene.add(new THREE.PointLightHelper(pointLight));

  // var directionalLight = new THREE.DirectionalLight( 0xffffff );
  // directionalLight.position.set( -5, 5, 5).normalize();
  // scene.add( directionalLight );
  // var pointlight = new THREE.PointLight(0x63d5ff, 1, 200);
  // pointlight.position.set(0, 0, 200);
  // scene.add( pointlight );
  // var pointlight2 = new THREE.PointLight(0xffffff, 1, 200);
  // pointlight2.position.set(-200, 200, 200);
  // scene.add( pointlight2 );
  // var pointlight3 = new THREE.PointLight(0xffffff, 1.5, 200);
  // pointlight3.position.set(-200, 200, 0);
  // scene.add( pointlight3 );

  // model 模型加载进度
  var onProgress = function (xhr) {
    if (xhr.lengthComputable) {
      const percentComplete = (xhr.loaded / xhr.total) * 100;
      // console.log('model ' + Math.round(percentComplete, 2) + '% downloaded');
    }
  };

  // 错误处理
  var onError = function (xhr) {};
  var includeMode = [
    "A栋第一层",
    "A栋第二层",
    "A栋第三层",
    "A栋第四层",
    "A栋第五层",
    "B栋第一层",
    "B栋第二层",
    "B栋第三层",
    "B栋第四层",
    "B栋第五层",
  ];
  // 加载一级模型GLTF
  createGLTF({
    dracoPath: cfg.draco_url,
    gltfPath: cfg.mole_url,
    completeCallback: function (gltf) {
      console.log("### gltf", gltf);
      const obj = gltf;
      obj.traverse(function (object) {
        if (object.isMesh) {
          // object.castShadow = true; //阴影
          // object.receiveShadow = true; //接受别人投的阴影
        }
      });
      for (k in obj.children) {
        if (
          includeMode.some((item) => obj.children[k].name.indexOf(item) > -1)
        ) {
          obj.children[k].castShadow = true;
          obj.children[k].receiveShadow = true;
          // obj.children[k].material = null;
        }
      }
      obj.traverse(function (child) {
        if (child instanceof THREE.Object3D) {
          if (includeMode.some((item) => child.name.indexOf(item) > -1)) {
            child.oldMaterial = child.material;
            child.castShadow = true; // 开启阴影
            clickObjects.push(child);
          }
          // if (child.name === '创新实训基地' || child.name === '圆锥体') {
          // 着重显示，可进入内部
          // clickObjects.push(child);
          // outlinePassRed.selectedObjects.push(child)
          // }
        }
      });

      // obj.emissive = 0x00ffff;
      // obj.ambient = 0x00ffff;
      // obj.rotation.x= 10/180*Math.PI;
      obj.position.y = 0;
      obj.position.z = 0;
      obj.scale.x = 5;
      obj.scale.y = 5;
      obj.scale.z = 5;
      obj.name = "build";
      // obj.rotation.y=-Math.PI;
      // obj.rotation.y = THREE.Math.degToRad(180)
      fxtreeObject[0] = obj;
      scene.add(obj);
      // obj.visible = false;
      if (mole1Loader == 100) {
        $("#fx-loading").hide();
        // fxtreeObject[0].visible = true;
        // makePerson(0,75,-90, 35, '建筑材料的哈哈哈这个是建筑', 'red');
      }
    },
    progress: function (persent) {
      console.log("### ###", persent);
      mole1Loader = persent;
      //datavFnc('modelProgress',parseInt((mole1Loader + mole2Loader + mole3Loader)/3))
      // $("#fx-loading").html(parseInt((mole1Loader + mole2Loader + mole3Loader)/3) + '% loading...')
    },
  });

  // 创建精灵模型
  // const map = new THREE.TextureLoader().load( '../../resources/img/back_btn.png' );
  // const material = new THREE.SpriteMaterial( { map: map } );
  // const sprite = new THREE.Sprite( material );
  // sprite.scale.set(100, 50, 1)
  // scene.add( sprite );
  // sprite.translateY(143);

  renderer = new THREE.WebGLRenderer({
    antialias: true,
    alpha: true,
    logarithmicDepthBuffer: true,
  });
  renderer.setClearColor(0xeeeeee, 0.0); // 透明背景
  renderer.physicallyCorrectLights = true;
  // renderer.outputEncoding = THREE.sRGBEncoding;
  renderer.outputEncoding = THREE.sRGBEncoding;
  renderer.gammaOutput = true;
  renderer.gammaFactor = 2.2;

  renderer.shadowMap.enabled = true;
  // renderer.setClearColor("#ccc"); // 背景色 0xffffcc
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(boxOffsetWidth, boxOffsetHeight);

  pmremGenerator = new THREE.PMREMGenerator(renderer);
  pmremGenerator.compileEquirectangularShader();

  renderer.toneMappingExposure = 1;
  treeContainer.append(renderer.domElement);

  new RGBELoader()
    .setDataType(THREE.UnsignedByteType)
    .load(cfg.mole_environment, function (texture) {
      const envMap = pmremGenerator.fromEquirectangular(texture).texture;
      // envMap.isPmremTexture = true;
      pmremGenerator.dispose();

      scene.environment = envMap; // 给场景添加环境光效果
      scene.background = "#ccc"; // 给场景添加背景图
    });

  // 返回按钮

  // var backBtn = document.getElementById("backBtn");
  // backBtn.onclick = function () {
  // 	console.log('currentMoles', currentMoles)
  // 	if (currentMoles == 2) {
  // 		datavFnc('valueChange', {'type': 'back', 'to': 1, 'from' : currentMoles})
  // 		// $("#space1").addClass("screen-change");
  // 		hideInLabel('装配机', true)
  // 		setupObjectScaleAnimation(fxtreeObject[1], { x: 1, y: 1, z: 1 }, { x: 0, y: 0, z: 0 }, 1000, 50, TWEEN.Easing.Linear.None, function(){
  // 			// $("#space1").addClass("screen-change-1");
  // 			currentMoles = 1; // 当前模型为1级
  // 			fxtreeObject[0].visible = true;
  // 			fxtreeObject[1].visible = false;
  // 			fxtreeObject[1].scale.x = 1;
  // 			fxtreeObject[1].scale.y = 1;
  // 			fxtreeObject[1].scale.z = 1;
  // 			var backBtn = document.getElementById("backBtn");
  // 			backBtn.style.display = 'none'
  // 			hideInLabel('综合大楼', false)
  // 		});
  // 	}
  // 	if (currentMoles == 3) {
  // 		datavFnc('valueChange', {'type': 'back', 'to': 2, 'from' : currentMoles})
  // 		// $("#space1").addClass("screen-change");
  // 		setupObjectScaleAnimation(fxtreeObject[2], { x: 0.1, y: 0.1, z: 0.1 }, { x: 0, y: 0, z: 0 }, 1000, 50, TWEEN.Easing.Linear.None, function(){
  // 			// $("#space1").addClass("screen-change-1");
  // 			currentMoles = 2; // 当前模型为2级
  // 			fxtreeObject[1].visible = true;
  // 			fxtreeObject[2].visible = false;
  // 			fxtreeObject[2].scale.x = 0.1;
  // 			fxtreeObject[2].scale.y = 0.1;
  // 			fxtreeObject[2].scale.z = 0.1;
  // 			hideInLabel('装配机', false)
  // 		});
  // 	}
  // }

  // 缩放
  // $("#space").addEventListener('resize', onWindowResize, false);
  // $("#space").mousemove(onDocumentMouseMove)
  // 单击事件
  // window.addEventListener("dblclick", onDocumentClick, false)
  treeContainer.addEventListener("contextmenu", onRightClick, false);
  treeContainer.addEventListener("click", onDocumentClick, false);
  treeContainer.addEventListener("mousemove", onDocumentMouseMove, false);
  $("#closepopup").on("click", function () {
    // 处理点击事件的代码
    hidePopup();
  });

  // 关闭按钮
  $("#imgClose").attr("src", cfg.img_colse);

  $("#space").append(
    `<style>#space::after{background-image:url('${cfg.bg_img_url}')}</style>`
  );

  $("#popup").css("background-image", `url('${cfg.popup_bg}')`);
}

// 返回按钮事件
function backBtnFnc() {
  if (currentMoles == 2) {
    //datavFnc('valueChange', {'type': 'back', 'to': 1, 'from' : currentMoles})
    // $("#space1").addClass("screen-change");
    // hideInLabel('装配机', true)
    setupObjectScaleAnimation(
      fxtreeObject[1],
      { x: 1, y: 1, z: 1 },
      { x: 0, y: 0, z: 0 },
      1000,
      500,
      TWEEN.Easing.Linear.None,
      function () {
        // $("#space1").addClass("screen-change-1");
        currentMoles = 1; // 当前模型为1级
        fxtreeObject[0].visible = true;
        fxtreeObject[1].visible = false;
        fxtreeObject[1].scale.x = 1;
        fxtreeObject[1].scale.y = 1;
        fxtreeObject[1].scale.z = 1;
        // var backBtn = document.getElementById("backBtn");
        // backBtn.style.display = 'none'
        // hideInLabel('综合大楼', false)
      }
    );
  }
  if (currentMoles == 3) {
    //datavFnc('valueChange', {'type': 'back', 'to': 2, 'from' : currentMoles})
    // $("#space1").addClass("screen-change");
    setupObjectScaleAnimation(
      fxtreeObject[2],
      { x: 0.2, y: 0.2, z: 0.2 },
      { x: 0, y: 0, z: 0 },
      1000,
      50,
      TWEEN.Easing.Linear.None,
      function () {
        // $("#space1").addClass("screen-change-1");
        currentMoles = 2; // 当前模型为2级
        fxtreeObject[1].visible = true;
        fxtreeObject[2].visible = false;
        fxtreeObject[2].scale.x = 0.2;
        fxtreeObject[2].scale.y = 0.2;
        fxtreeObject[2].scale.z = 0.2;
        // hideInLabel('装配机', false)
      }
    );
  }
}

function onWindowResize(w, h) {
  let pox = treeContainer.getBoundingClientRect();
  positionY = pox.y;
  positionX = pox.x;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
}

function setWidthAndHeight(w, h) {
  boxOffsetWidth = w;
  boxOffsetHeight = h;
}

function createMtlObj(options) {
  var mtlLoader = new MTLLoader();
  mtlLoader.setPath(options.mtlPath);
  mtlLoader.load(options.mtlFileName, function (materials) {
    materials.preload();
    var objLoader = new OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath(options.objPath);
    objLoader.load(
      options.objFileName,
      function (obj) {
        // console.log('obj11', obj)
        if (typeof options.completeCallback == "function") {
          options.completeCallback(obj);
        }
      },
      function (xhr) {
        if (xhr.lengthComputable) {
          var percentComplete = (xhr.loaded / xhr.total) * 100;
          if (typeof options.progress == "function") {
            options.progress(Math.round(percentComplete, 2));
          }
          //console.log( Math.round(percentComplete, 2) + '% downloaded' );
        }
      },
      function (error) {
        console.log(error);
      }
    );
  });
}

function createGLTF(options) {
  const dracoLoader = new DRACOLoader();
  dracoLoader.setDecoderPath(options.dracoPath);
  dracoLoader.setDecoderConfig({ type: "js" });
  //dracoLoader.preload();//1请求解码器库(如果尚未加载)、---目前这个设置开启后，解码时间过长，屏蔽后目前无影响
  gltfLoader.setDRACOLoader(dracoLoader);
  gltfLoader.load(
    options.gltfPath,
    function (gltf) {
      if (typeof options.completeCallback == "function") {
        options.completeCallback(gltf.scene);
      }
    },
    function (xhr) {
      if (xhr.lengthComputable) {
        var percentComplete = (xhr.loaded / xhr.total) * 100;
        if (typeof options.progress == "function") {
          options.progress(Math.round(percentComplete, 2));
        }
        //console.log( Math.round(percentComplete, 2) + '% downloaded' );
      }
    },
    function (error) {
      console.log(error);
    }
  );
}

// 控制
function initControls(fnc) {
  if (fnc) {
    datavFnc = fnc;
  }
  treeControls = new OrbitControls(camera, treeContainer);
  // treeControls = new OrbitControls(camera, renderer.domElement);

  // 如果使用animate方法时，将此函数删除

  //treeControls.addEventListener( 'change', render );

  // 使动画循环使用时阻尼或自转 意思是否有惯性

  // treeControls.enableDamping = true;

  //动态阻尼系数 就是鼠标拖拽旋转灵敏度

  //上下翻转的最大角度
  treeControls.maxPolarAngle = 1.5;
  //上下翻转的最小角度
  treeControls.minPolarAngle = 0.3;

  //是否可以缩放
  treeControls.enableZoom = true;

  //是否自动旋转
  treeControls.autoRotate = false;

  treeControls.enablePan = true;
  // treeControls.update();
  // TWEEN.update();
  // scene.position.x=0;
  // scene.position.y=0;
  // scene.position.z=0;
  // camera.position.x=10;
  // camera.position.y=10;
  // camera.position.z=5;
  // camera.lookAt(scene.position);
  // renderer.render(scene, camera);
}

function animate() {
  treeControls.update();
  animationId = requestAnimationFrame(animate);
  TWEEN.update();
  render();
}

function render() {
  if (_isRotateing) {
    //用户点击行为执行旋转动画
    // var newCameraPos = Math3D.getAxis2dByAngle(_userView.dmy.theta, _userView.dmy.r);
    // camera.position.x = newCameraPos.x;
    // camera.position.y = _userView.dmy.y;
    // camera.position.z = newCameraPos.y;
  } else {
    //自动旋转
    // var newCameraPos = Math3D.getRotateAxis2d({
    // 	x: camera.position.x,
    // 	y: camera.position.z
    // }, -0.001, 0);
    // camera.position.x = newCameraPos.x;
    // camera.position.z = newCameraPos.y;
  }
  // debugger
  camera.lookAt(scene.position);

  renderer.render(scene, camera);
}

// 点击事件回传值到datav
function setDatavClick(fnc, name, obj) {
  console.log("fnc,name-obj", name, obj);
  fnc(name, obj);
}

/**
 * 相机点到点移动
 * @current1 相机当前的位置
 * @target1 相机的controls的target
 * @current2 新相机的目标位置
 * @target2 新的controls的target
 */
let tweenObj;
function animateCamera(current1, target1, current2, target2, times) {
  let positionVar = {
    x1: current1.x,
    y1: current1.y,
    z1: current1.z,
    x2: target1.x,
    y2: target1.y,
    z2: target1.z,
  };
  //关闭控制器
  treeControls.enabled = false;
  tweenObj = new TWEEN.Tween(positionVar);
  tweenObj.to(
    {
      x1: current2.x,
      y1: current2.y,
      z1: current2.z,
      x2: target2.x,
      y2: target2.y,
      z2: target2.z,
    },
    times
  );

  tweenObj.onUpdate(function () {
    camera.position.x = positionVar.x1;
    camera.position.y = positionVar.y1;
    camera.position.z = positionVar.z1;
    treeControls.target.x = positionVar.x2;
    treeControls.target.y = positionVar.y2;
    treeControls.target.z = positionVar.z2;
    treeControls.update();
    // console.log(positionVar);
  });

  tweenObj.onComplete(function () {
    ///开启控制器
    treeControls.enabled = true;
    // camera.fov -= 5;
  });

  tweenObj.easing(TWEEN.Easing.Cubic.InOut);
  // tween22.easing(TWEEN.Easing.Cubic.Out);
  tweenObj.start();
}

/**
 * 鼠标右键单击
 * @param {*} event
 */
function onRightClick(event) {
  event.preventDefault();
  if (event.button === 2) {
    animateCamera(
      camera.position,
      treeControls.target,
      camDefaultPosition,
      camDefaultTarget,
      1000
    );
    datavFnc("valueChange", { type: "click", name: "All" });
  }
}

// 鼠标点击事件
function onDocumentClick(event) {
  event.preventDefault();
  if (hoverSelectObject) {
    hoverSelectObject.material = hoverSelectObject.oldMaterial;
    hoverSelectObject = null;
  }
  if (selectObject) {
    // console.log(selectObject);
    // selectObject.material.color.set("#fff");
    selectObject = null;
    $("#label").hide();
  }
  var intersects = getIntersects(event, event.layerX, event.layerY);
  // console.log('intersects',intersects)
  if (intersects.length > 0) {
    var res = intersects.filter(function (res) {
      return res && res.object;
    })[0];
    if (res && res.object.parent) {
      hoverSelectObject = res.object.parent;
      document.body.style.cursor = "pointer";
      selectObject = res.object.parent;
      console.log("selectObject", selectObject);
      // selectObject.material.color.set("#fff");
      // renderDiv(selectObject);
      // rotateTo(intersects[0])
      // console.log('selectObject.name',selectObject.name)
      //datavFnc('valueChange', {type: 'click', 'name': selectObject.name});
      if (
        selectObject.name.indexOf("A栋第五层") >= 0 ||
        selectObject.name.indexOf("A栋第四层") >= 0 ||
        selectObject.name.indexOf("A栋第三层") >= 0 ||
        selectObject.name.indexOf("A栋第二层") >= 0 ||
        selectObject.name.indexOf("A栋第一层") >= 0 ||
        selectObject.name.indexOf("B栋第五层") >= 0 ||
        selectObject.name.indexOf("B栋第四层") >= 0 ||
        selectObject.name.indexOf("B栋第三层") >= 0 ||
        selectObject.name.indexOf("B栋第二层") >= 0 ||
        selectObject.name.indexOf("B栋第一层") >= 0
      ) {
        showPopup(selectObject.name);
      } else if (
        selectObject.name.indexOf("A栋") >= 0 ||
        selectObject.name.indexOf("B栋") >= 0 ||
        selectObject.name.indexOf("C栋") >= 0 ||
        selectObject.name.indexOf("D栋") >= 0 ||
        selectObject.name.indexOf("E栋") >= 0
      ) {
        // changeScene()
        if (fxtreeObject[0]) {
          // scene.children[5].visible = false;
          // hideInLabel('综合大楼', true)// 修改显示隐藏状态
          // var thisevent = event || window.event;
          // $("#space1").addClass("screen-change");
          // setupObjectScaleAnimation(fxtreeObject[0], { x: 1, y: 1, z: 1 }, { x: 2, y: 2, z: 2 }, 1000, 50, TWEEN.Easing.Linear.None, function(){
          // 	// $("#space1").addClass("screen-change-1");
          // 	// currentMoles = 2; // 当前模型为2级
          // 	// fxtreeObject[0].visible = false;
          // 	// fxtreeObject[0].visible = true;
          // 	// fxtreeObject[0].scale.x = 1;
          // 	// fxtreeObject[0].scale.y = 1;
          // 	// fxtreeObject[0].scale.z = 1;
          // 	console.log("我进来了")
          // 	// //停止转动
          // 	// cancelAnimationFrame(animationId);
          // 	// var backBtn = document.getElementById("backBtn");
          // 	// backBtn.style.display = 'block'
          // 	// makePerson(-40,40,40, 25, '装配机', 'red');
          // });

          let dmyStop = {};
          let point = intersects[0].point;
          const worldPoint = selectObject.getWorldPosition();
          const paiX = worldPoint.x;
          const paiY = worldPoint.y;
          const paiZ = worldPoint.z;
          // x: -180, y: 1000, z: -1520
          // console.log("--", paiX);
          // console.log("--", paiY);
          // console.log("--", paiZ);
          // console.log("selectObject.世界坐标：", worldPoint);
          // console.log("selectObject.名称：", selectObject.name);
          const worldPointNoew = {
            x: paiX,
            y: paiY,
            z: paiZ,
          };
          if (selectObject.name.indexOf("A栋") >= 0) {
            dmyStop.y = 3.807166353164768; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.x = -2.672766849899645; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.z = -11.785370137282875; //旋转到用户点击点所在位置时摄像机Y点坐标
          } else if (selectObject.name.indexOf("B栋") >= 0) {
            dmyStop.y = 2.7634244254784437; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.x = 5.3125036024085155; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.z = -11.165748450794302; //旋转到用户点击点所在位置时摄像机Y点坐标
          } else if (selectObject.name.indexOf("C栋") >= 0) {
            dmyStop.y = 3.8567681325974825; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.x = 0.4442230066016044; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.z = -4.754391106169663; //旋转到用户点击点所在位置时摄像机Y点坐标
          } else if (selectObject.name.indexOf("D栋") >= 0) {
            dmyStop.y = 6.188339707574396; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.x = -0.690902031520598; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.z = 13.841659126418197; //旋转到用户点击点所在位置时摄像机Y点坐标
          } else if (selectObject.name.indexOf("E栋") >= 0) {
            dmyStop.y = 5.262310741681007; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.x = 4.9965390022117875; //旋转到用户点击点所在位置时摄像机Y点坐标
            dmyStop.z = 0.40839050571445756; //旋转到用户点击点所在位置时摄像机Y点坐标
          }

          // createPoint(worldPoint.x, worldPoint.y, worldPoint.z);
          // resetMeshMaterial()
          //回到初始视角
          animateCamera(
            camera.position,
            treeControls.target,
            camDefaultPosition,
            camDefaultTarget,
            1000
          );
          setTimeout(() => {
            oldCamPosition = JSON.parse(JSON.stringify(dmyStop));
            oldCamTarget = JSON.parse(JSON.stringify(intersects[0].point));
            // animateCamera(camDefaultPosition, treeControls.target, cameraPositionByName[selectObject.name].current, worldPoint, 1500)
            animateCamera(
              camDefaultPosition,
              treeControls.target,
              oldCamPosition,
              worldPointNoew,
              1500
            );
            // modelAddBLN(intersects[0].object)
          }, 1000);
        }
		  datavFnc("valueChange", { buildingId: selectObject.name });
      } else {
        document.body.style.cursor = "default";
        hidePopup();
      }
    }
    
  } else {
    hidePopup();
  }
}

// 鼠标hover事件
function onDocumentMouseMove(event) {
  event.preventDefault();
  let pox = treeContainer.getBoundingClientRect();
  // console.log("1--", camera.position.x);
  // console.log("1--", camera.position.y);
  // console.log("1--", camera.position.z);
  if (hoverSelectObject) {
    hoverSelectObject.material = hoverSelectObject.oldMaterial;
    hoverSelectObject = null;
  }

  // let xx = ((event.clientX - pox.left)/treeContainer.offsetWidth) * 2 - 1; // 标准设备横坐标
  // let yy = -((event.clientY - pox.top)/treeContainer.offsetHeight) * 2 + 1; // 标准设备纵坐标
  let xx = ((event.clientX - pox.left) / pox.width) * 2 - 1; // 标准设备横坐标
  let yy = -((event.clientY - pox.top) / pox.height) * 2 + 1; // 标准设备纵坐标

  let standardVector = new THREE.Vector3(xx, yy, 1); // 标准设备坐标
  // 标准设备坐标转世界坐标
  let worldVector = standardVector.unproject(camera);
  // 射线投射方向单位向量(worldVector坐标减相机位置坐标)
  let rays = worldVector.sub(camera.position).normalize();
  // 创建射线投射器对象
  let rayCasters = new THREE.Raycaster(camera.position, rays);
  // 返回射线选中的对象 第二个参数如果不填 默认是false
  let intersects = rayCasters.intersectObjects(clickObjects);

  // ---
  // raycAsix.x = ((event.pageX - pox.x) / treeContainer.offsetWidth) * 2 - 1;
  // raycAsix.y = -((event.pageY - pox.y) / treeContainer.offsetHeight) * 2 + 1;

  // _raycaster.setFromCamera(raycAsix, camera);
  // var intersects = _raycaster.intersectObjects(clickObjects);
  // ---
  console.log("intersects", intersects);
  if (intersects.length > 0) {
    var res = intersects.filter(function (res) {
      return res && res.object;
    })[0];
    if (res && res.object) {
      hoverSelectObject = res.object;
      document.body.style.cursor = "pointer";
      // outlineObj(res.object)
      // clickObjects[0].add(
      //   new THREE.LineSegments(intersects[0].object, lineMaterial)
      // );
      intersects[0].object.material = new THREE.MeshBasicMaterial({
        color: "#ff1b40",
      });
      intersects[0].object.material.transparent = true;
      // intersects[0].object.material.wireframe = true;
      intersects[0].object.material.opacity = 0.5;
    }
  } else {
    document.body.style.cursor = "default";
  }
}

var _userView = {}; //用于存储相机theta（水平夹角） phi（竖立夹角） 和离中心点坐标的距离R，使用这三个变量去修改相机的位置
function rotateTo(obj) {
  //
  _isRotateing = true;
  treeControls.enabled = false;
  var point = obj.point;
  var pointAngle = Math3D.get3DAngle(point.x, point.y, point.z); //点击点的角度和球半径
  var toAngle = {
    //需要旋转到的用户视角的角度和半径
    theta: pointAngle.theta,
    phi: (30 / 180) * Math.PI,
    r: 1000,
  };
  _userView.cameraPosTo = Math3D.get3DAxis(
    toAngle.theta,
    toAngle.phi,
    toAngle.r
  ); //旋转用户视角停止时摄像机位置
  _userView.dmy = {};
  _userView.dmy.theta = Math3D.getAngleByAxis2d({
    x: camera.position.x,
    y: camera.position.z,
  }); //当前摄像机与Z轴的水平夹角
  _userView.dmy.r = Math.sqrt(
    camera.position.x * camera.position.x +
      camera.position.z * camera.position.z
  ); //当前摄像机离坐标轴原点的水平距离
  _userView.dmy.y = camera.position.y; //当前摄像机的Y点坐标

  var dmyStop = {}; //相机将到移动到的最终位置
  dmyStop.theta = Math3D.getAngleByAxis2d({
    x: point.x,
    y: point.z,
  }); //旋转到用户点击点所在位置时摄像机与Z轴的水平夹角
  dmyStop.r = 1000; //旋转到用户点击点所在位置时摄像机与坐标原点的水平距离
  dmyStop.y = 300; //旋转到用户点击点所在位置时摄像机Y点坐标
  var tween = new TWEEN.Tween(_userView.dmy)
    .to(dmyStop, 1000)
    .easing(TWEEN.Easing.Quadratic.InOut)
    .onComplete(function () {
      _isRotateing = false;
      treeControls.enabled = true;
    })
    .start(); //设置缓动动画
}

//鼠标点击物体事件
// var raycaster = new THREE.Raycaster();
// var mouseVector = new THREE.Vector2();

function getIntersects(x, y) {
  //将鼠标位置转换成设备坐标。x和y方向的取值范围是(-1 to 1)
  let pox = treeContainer.getBoundingClientRect();
  // x = (x / (boxOffsetWidth - positionX)) * 2 - 1;
  // y = -(y / (boxOffsetHeight - positionY)) * 2 + 1;

  x = ((event.pageX - pox.x) / pox.width) * 2 - 1;
  y = -((event.pageY - pox.y) / pox.height) * 2 + 1;
  raycAsix.set(x, y);

  //通过摄像机和鼠标位置更新射线
  _raycaster.setFromCamera(raycAsix, camera);

  // 返回物体和射线的焦点
  // return raycaster.intersectObjects(fxtreeObject[0].children)
  return _raycaster.intersectObject(fxtreeObject[0], true);
}

function myCameraTweenByAnyAxis(camera, angle, segs, during) {
  var x = camera.position.x;
  var y = camera.position.y;
  var z = camera.position.z;

  //相机向量（指向场景中心）
  var v1 = new THREE.Vector3(x, y, z);

  //求旋转轴，v1的垂直单位向量,令x=1,y=1,z=-(v1.x+v1.y)/v1.z
  var n = new THREE.Vector3(1, 0, (-1.0 * v1.x) / v1.z).normalize();

  var endPosArray = new Array();

  var perAngle = angle / segs;

  for (var i = 1; i <= segs; i++) {
    var sinDelta = Math.sin(THREE.Math.degToRad(i * perAngle));
    var cosDelta = Math.cos(THREE.Math.degToRad(i * perAngle));

    var tempX =
      x * (n.x * n.x * (1 - cosDelta) + cosDelta) +
      y * (n.x * n.y * (1 - cosDelta) - n.z * sinDelta) +
      z * (n.x * n.z * (1 - cosDelta) + n.y * sinDelta);
    var tempY =
      x * (n.x * n.y * (1 - cosDelta) + n.z * sinDelta) +
      y * (n.y * n.y * (1 - cosDelta) + cosDelta) +
      z * (n.y * n.z * (1 - cosDelta) - n.x * sinDelta);
    var tempZ =
      x * (n.x * n.z * (1 - cosDelta) - n.y * sinDelta) +
      y * (n.y * n.z * (1 - cosDelta) + n.x * sinDelta) +
      z * (n.z * n.z * (1 - cosDelta) + cosDelta);

    var endPos = { x: tempX, y: tempY, z: tempZ };

    //console.log(endPos);
    endPosArray.push(endPos);
  }

  var flag = 0;
  var id = setInterval(function () {
    if (flag == segs) {
      clearInterval(id);
    } else {
      camera.position.x = endPosArray[flag].x;
      camera.position.y = endPosArray[flag].y;
      camera.position.z = endPosArray[flag].z;

      camera.updateMatrix();

      flag++;
    }
  }, during / segs);
}

function setupObjectScaleAnimation(
  object1,
  source,
  target,
  duration,
  delay,
  easing,
  complete
) {
  var l_delay = delay !== undefined ? delay : 0;
  var l_easing = easing !== undefined ? easing : TWEEN.Easing.Linear.None;

  new TWEEN.Tween(source)
    .to(target, duration)
    .delay(l_delay)
    .easing(l_easing)
    .onUpdate(function () {
      object1.scale.copy(source);
    })
    .onComplete(complete)
    .start();
}

// 按钮点击事件

// var btn1 = document.getElementById("btn1");
// btn1.onclick = function () {
// 	let ids = $(container).attr('id');
// 	if (ids != 'space1') {
// 		renderer.clearDepth();
// 		// scene = null;
// 		// object = null;
// 		// camera  = null;
// 		// controls = null;
// 		// empty(container);
// 		$("#space").empty()
// 		$("#space2").empty()
// 		container = document.getElementById("space1")
// 		mtlPath = "/resources/models/obj/mole1/"
// 		objPath = "/resources/models/obj/mole1/"
// 		threeInit()
// 		initControls();
// 		animate();
// 	}
// }
// var btn2 = document.getElementById("btn2");
// btn2.onclick = function () {
// 	let ids = $(container).attr('id');
// 	if (ids != 'space') {
// 		renderer.clearDepth();
// 		$("#space1").empty()
// 		$("#space2").empty()
// 		container = document.getElementById("space")
// 		mtlPath = "/resources/models/obj/mole/"
// 		objPath = "/resources/models/obj/mole/"
// 		threeInit()
// 		initControls();
// 		animate();
// 	}
// }
const bodyRadiusTop = 0.4;
const bodyRadiusBottom = 0.2;
// const bodyHeight = 150;
const bodyRadialSegments = 6;
const bodyGeometry = new THREE.CylinderBufferGeometry(
  bodyRadiusTop,
  bodyRadiusBottom,
  150,
  bodyRadialSegments
);
const headRadius = bodyRadiusTop * 0.8;
const headLonSegments = 12;
const headLatSegments = 5;
const headGeometry = new THREE.SphereBufferGeometry(
  headRadius,
  headLonSegments,
  headLatSegments
);

// 显示隐藏指定的模型
function hideInLabel(name, state) {
  const models = scene.children;
  if (models && models.length) {
    const curModels = models.filter((item) => {
      return item.name == name;
    });
    if (curModels && curModels.length) {
      curModels.map((el) => {
        el.visible = !state;
      });
    }
  }
}
// 清除指定的模型
function removeInLabel(name) {
  const models = scene.children;
  if (models && models.length) {
    const curModels = models.filter((item) => {
      return item.name == name;
    });
    if (curModels && curModels.length) {
      curModels.map((el) => {
        scene.remove(el);
      });
    }
  }
}

function makeLabelCanvas(baseWidth, baseHeight, size, name) {
  const borderSize = 50;
  const ctx = document.createElement("canvas").getContext("2d");
  const font = `${size}px bold sans-serif`;
  ctx.font = font;
  // measure how long the name will be
  const textWidth = ctx.measureText(name).width;

  const doubleBorderSize = borderSize * 2;
  const width = baseWidth + doubleBorderSize;
  const height = baseHeight + doubleBorderSize;
  ctx.canvas.width = width;
  ctx.canvas.height = height;

  // need to set font again after resizing canvas
  ctx.font = font;
  ctx.textBaseline = "middle";
  ctx.textAlign = "left";
  // 设置背景框

  ctx.fillStyle = "rgba(0, 149, 255, .69)";
  ctx.fillRect(0, 0, width, height);

  // scale to fit but don't stretch
  // const scaleFactor = Math.min(1, baseWidth / textWidth);
  // ctx.translate(width / 2, height / 2);
  // ctx.scale(scaleFactor, 1);

  //    let gradient = ctx.createRadialGradient(width/2, height/2,0,width/2,height/2,width/2);
  // gradient.addColorStop(0,'#f2fcfe');
  // gradient.addColorStop(0.2,'rgba(139,69,19,1)');
  // gradient.addColorStop(0.4,'rgba(139,69,19,1)');
  // gradient.addColorStop(1,'#1c92d2');
  ctx.fillStyle = "#fff";
  // ctx.fillText(name, 0, 0);
  //文字换行
  let len = parseInt(name.length / 10);
  for (let i = 0; i < len + 1; i++) {
    let space = 10;
    if (i === len) {
      space = name.length - len * 10;
    }
    let word = name.substr(i * 10, space);
    ctx.fillText(word, doubleBorderSize, 90 * (i + 1));
  }

  return ctx.canvas;
}
// 创建公告牌
function makePerson(x, y, z, bodyHeight, name, color) {
  const canvas = makeLabelCanvas(800, 300, 70, name);
  const texture = new THREE.CanvasTexture(canvas);
  // because our canvas is likely not a power of 2
  // in both dimensions set the filtering appropriately.
  texture.minFilter = THREE.LinearFilter;
  texture.wrapS = THREE.ClampToEdgeWrapping;
  texture.wrapT = THREE.ClampToEdgeWrapping;

  const labelMaterial = new THREE.SpriteMaterial({
    map: texture,
    transparent: true,
  });
  const bodyMaterial = new THREE.SpriteMaterial({
    // color,
    map: new THREE.TextureLoader().load("./images/1.png"),
    // flatShading: true,
  });

  const root = new THREE.Object3D();
  root.position.x = x;
  root.name = name;
  // root.position.z = z;

  // const body = new THREE.Mesh(bodyGeometry, bodyMaterial);

  // const material = new THREE.SpriteMaterial( { map: map } );
  const body = new THREE.Sprite(bodyMaterial);
  body.scale.set(10, 25, 1);

  root.add(body);
  body.position.y = y;
  body.position.z = z;

  // const head = new THREE.Mesh(headGeometry, bodyMaterial);
  // root.add(head);
  // head.position.y = bodyHeight + headRadius * 1.1;

  // if units are meters then 0.01 here makes size
  // of the label into centimeters.

  const labelBaseScale = 0.1;
  const label = new THREE.Sprite(labelMaterial);
  root.add(label);
  label.position.y = bodyHeight + y + 3;
  label.position.z = z;
  label.scale.x = canvas.width * labelBaseScale;
  label.scale.y = canvas.height * labelBaseScale;
  scene.add(root);
  return root;
}
function showPopup(buildingId) {
  const popup = document.getElementById("popup");
  const popup1 = document.getElementById("popup1");
  //清楚子集
  $(popup1).empty();
  var imgurl;
  if (buildingId.indexOf("A栋第五层") >= 0) {
    imgurl = overallcfg.lc_a_1;
    datavFnc("valueChange", { buildingId: "A", floorId: 5 });
  } else if (buildingId.indexOf("A栋第四层") >= 0) {
    imgurl = overallcfg.lc_a_2;
    datavFnc("valueChange", { buildingId: "A", floorId: 4 });
  } else if (buildingId.indexOf("A栋第三层") >= 0) {
    imgurl = overallcfg.lc_a_3;
    datavFnc("valueChange", { buildingId: "A", floorId: 3 });
  } else if (buildingId.indexOf("A栋第二层") >= 0) {
    imgurl = overallcfg.lc_a_4;
    datavFnc("valueChange", { buildingId: "A", floorId: 2 });
  } else if (buildingId.indexOf("A栋第一层") >= 0) {
    imgurl = overallcfg.lc_a_5;
    datavFnc("valueChange", { buildingId: "A", floorId: 1 });
  } else if (buildingId.indexOf("B栋第五层") >= 0) {
    imgurl = overallcfg.lc_b_5;
    datavFnc("valueChange", { buildingId: "B", floorId: 5 });
  } else if (buildingId.indexOf("B栋第四层") >= 0) {
    imgurl = overallcfg.lc_b_4;
    datavFnc("valueChange", { buildingId: "B", floorId: 5 });
  } else if (buildingId.indexOf("B栋第三层") >= 0) {
    imgurl = overallcfg.lc_b_3;
    datavFnc("valueChange", { buildingId: "B", floorId: 5 });
  } else if (buildingId.indexOf("B栋第二层") >= 0) {
    imgurl = overallcfg.lc_b_2;
    datavFnc("valueChange", { buildingId: "B", floorId: 5 });
  } else if (buildingId.indexOf("B栋第一层") >= 0) {
    imgurl = overallcfg.lc_b_1;
    datavFnc("valueChange", { buildingId: "B", floorId: 5 });
  }
  $(popup1).append(`<img src="${imgurl}" style="width: 80%; height: 80%;"> `);
  popup.style.display = "block";
}
function hidePopup() {
  document.getElementById("popup").style.display = "none";
}

export {
  animate,
  threeInit,
  initControls,
  setWidthAndHeight,
  onWindowResize,
  hideInLabel,
  removeInLabel,
  makePerson,
  backBtnFnc,
};
